<template>
  <el-dialog 
    :title="dialogTitle" 
    :visible.sync="dialogVisible" 
    width="900px" 
    append-to-body
    @close="handleClose"
  >
    <el-tabs v-model="activeTab" type="card">
      <!-- POS设备管理 -->
      <el-tab-pane label="POS设备管理" name="devices">
        <div class="relation-manage">
          <div class="available-section">
            <h4>可用POS设备</h4>
            <el-table 
              :data="availableDevices" 
              height="300"
              @selection-change="handleDeviceSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column label="设备编码" prop="deviceCode" width="120" />
              <el-table-column label="设备名称" prop="deviceName" />
              <el-table-column label="设备类型" prop="deviceType" width="100">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.pos_device_type" :value="scope.row.deviceType"/>
                </template>
              </el-table-column>
              <el-table-column label="状态" prop="status" width="80">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="当前柜组" prop="currentGroupName" width="120">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.currentGroupName" size="mini" type="warning">
                    {{ scope.row.currentGroupName }}
                  </el-tag>
                  <span v-else style="color: #999;">未分配</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <div class="operation-section">
            <el-button 
              type="primary" 
              :disabled="selectedDevices.length === 0"
              @click="assignDevices"
            >
              分配选中设备 ({{ selectedDevices.length }})
            </el-button>
            <el-button 
              type="danger" 
              :disabled="selectedDevices.length === 0"
              @click="removeDevices"
            >
              移除选中设备
            </el-button>
          </div>
          
          <div class="assigned-section">
            <h4>已分配POS设备</h4>
            <el-table :data="assignedDevices" height="200">
              <el-table-column label="设备编码" prop="deviceCode" width="120" />
              <el-table-column label="设备名称" prop="deviceName" />
              <el-table-column label="设备类型" prop="deviceType" width="100">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.pos_device_type" :value="scope.row.deviceType"/>
                </template>
              </el-table-column>
              <el-table-column label="状态" prop="status" width="80">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button 
                    size="mini" 
                    type="text" 
                    icon="el-icon-delete"
                    @click="removeDevice(scope.row)"
                  >移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      
      <!-- 收银员管理 -->
      <el-tab-pane label="收银员管理" name="cashiers">
        <div class="relation-manage">
          <div class="available-section">
            <h4>可用收银员</h4>
            <el-table 
              :data="availableCashiers" 
              height="300"
              @selection-change="handleCashierSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column label="收银员编码" prop="cashierCode" width="120" />
              <el-table-column label="收银员姓名" prop="cashierName" />
              <el-table-column label="联系电话" prop="phone" width="120" />
              <el-table-column label="状态" prop="status" width="80">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="已管理柜组" prop="managedGroups" width="150">
                <template slot-scope="scope">
                  <el-tag 
                    v-for="group in scope.row.managedGroups" 
                    :key="group.groupId"
                    size="mini" 
                    type="info"
                    style="margin-right: 5px;"
                  >
                    {{ group.groupName }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <div class="operation-section">
            <el-button 
              type="primary" 
              :disabled="selectedCashiers.length === 0"
              @click="assignCashiers"
            >
              分配选中收银员 ({{ selectedCashiers.length }})
            </el-button>
            <el-button 
              type="danger" 
              :disabled="selectedCashiers.length === 0"
              @click="removeCashiers"
            >
              移除选中收银员
            </el-button>
          </div>
          
          <div class="assigned-section">
            <h4>已分配收银员</h4>
            <el-table :data="assignedCashiers" height="200">
              <el-table-column label="收银员编码" prop="cashierCode" width="120" />
              <el-table-column label="收银员姓名" prop="cashierName" />
              <el-table-column label="联系电话" prop="phone" width="120" />
              <el-table-column label="状态" prop="status" width="80">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button 
                    size="mini" 
                    type="text" 
                    icon="el-icon-delete"
                    @click="removeCashier(scope.row)"
                  >移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">关 闭</el-button>
      <el-button type="primary" @click="handleSave">保存配置</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listDevice } from "@/api/pos/device";
import { listCashier } from "@/api/pos/cashier";
import { getGroupDevices, getGroupCashiers, setGroupDevices, setGroupCashiers } from "@/api/pos/group";

export default {
  name: "GroupRelationManage",
  dicts: ['sys_normal_disable', 'pos_device_type'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    groupData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogVisible: false,
      activeTab: 'devices',
      // 设备相关
      availableDevices: [],
      assignedDevices: [],
      selectedDevices: [],
      // 收银员相关
      availableCashiers: [],
      assignedCashiers: [],
      selectedCashiers: []
    };
  },
  computed: {
    dialogTitle() {
      return `柜组关联管理 - ${this.groupData.groupName || ''}`;
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
      if (val) {
        this.loadData();
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val);
    }
  },
  methods: {
    /** 加载数据 */
    async loadData() {
      await Promise.all([
        this.loadAvailableDevices(),
        this.loadAssignedDevices(),
        this.loadAvailableCashiers(),
        this.loadAssignedCashiers()
      ]);
    },
    
    /** 加载可用设备 */
    async loadAvailableDevices() {
      try {
        const response = await listDevice({ status: '0' });
        this.availableDevices = response.rows || [];
      } catch (error) {
        this.$modal.msgError("加载可用设备失败");
      }
    },
    
    /** 加载已分配设备 */
    async loadAssignedDevices() {
      try {
        const response = await getGroupDevices(this.groupData.groupId);
        this.assignedDevices = response.data || [];
      } catch (error) {
        this.$modal.msgError("加载已分配设备失败");
      }
    },
    
    /** 加载可用收银员 */
    async loadAvailableCashiers() {
      try {
        const response = await listCashier({ status: '0' });
        this.availableCashiers = response.rows || [];
      } catch (error) {
        this.$modal.msgError("加载可用收银员失败");
      }
    },
    
    /** 加载已分配收银员 */
    async loadAssignedCashiers() {
      try {
        const response = await getGroupCashiers(this.groupData.groupId);
        this.assignedCashiers = response.data || [];
      } catch (error) {
        this.$modal.msgError("加载已分配收银员失败");
      }
    },
    
    /** 设备选择变化 */
    handleDeviceSelectionChange(selection) {
      this.selectedDevices = selection;
    },
    
    /** 收银员选择变化 */
    handleCashierSelectionChange(selection) {
      this.selectedCashiers = selection;
    },
    
    /** 分配设备 */
    async assignDevices() {
      if (this.selectedDevices.length === 0) {
        this.$modal.msgWarning("请选择要分配的设备");
        return;
      }
      
      try {
        const deviceIds = this.selectedDevices.map(device => device.deviceId);
        await setGroupDevices(this.groupData.groupId, deviceIds);
        this.$modal.msgSuccess("设备分配成功");
        await this.loadAssignedDevices();
        await this.loadAvailableDevices();
        this.selectedDevices = [];
      } catch (error) {
        this.$modal.msgError("设备分配失败");
      }
    },
    
    /** 移除设备 */
    async removeDevices() {
      if (this.selectedDevices.length === 0) {
        this.$modal.msgWarning("请选择要移除的设备");
        return;
      }
      
      try {
        const deviceIds = this.selectedDevices.map(device => device.deviceId);
        await setGroupDevices(this.groupData.groupId, deviceIds, 'remove');
        this.$modal.msgSuccess("设备移除成功");
        await this.loadAssignedDevices();
        await this.loadAvailableDevices();
        this.selectedDevices = [];
      } catch (error) {
        this.$modal.msgError("设备移除失败");
      }
    },
    
    /** 移除单个设备 */
    async removeDevice(device) {
      try {
        await setGroupDevices(this.groupData.groupId, [device.deviceId], 'remove');
        this.$modal.msgSuccess("设备移除成功");
        await this.loadAssignedDevices();
        await this.loadAvailableDevices();
      } catch (error) {
        this.$modal.msgError("设备移除失败");
      }
    },
    
    /** 分配收银员 */
    async assignCashiers() {
      if (this.selectedCashiers.length === 0) {
        this.$modal.msgWarning("请选择要分配的收银员");
        return;
      }
      
      try {
        const cashierIds = this.selectedCashiers.map(cashier => cashier.cashierId);
        await setGroupCashiers(this.groupData.groupId, cashierIds);
        this.$modal.msgSuccess("收银员分配成功");
        await this.loadAssignedCashiers();
        await this.loadAvailableCashiers();
        this.selectedCashiers = [];
      } catch (error) {
        this.$modal.msgError("收银员分配失败");
      }
    },
    
    /** 移除收银员 */
    async removeCashiers() {
      if (this.selectedCashiers.length === 0) {
        this.$modal.msgWarning("请选择要移除的收银员");
        return;
      }
      
      try {
        const cashierIds = this.selectedCashiers.map(cashier => cashier.cashierId);
        await setGroupCashiers(this.groupData.groupId, cashierIds, 'remove');
        this.$modal.msgSuccess("收银员移除成功");
        await this.loadAssignedCashiers();
        await this.loadAvailableCashiers();
        this.selectedCashiers = [];
      } catch (error) {
        this.$modal.msgError("收银员移除失败");
      }
    },
    
    /** 移除单个收银员 */
    async removeCashier(cashier) {
      try {
        await setGroupCashiers(this.groupData.groupId, [cashier.cashierId], 'remove');
        this.$modal.msgSuccess("收银员移除成功");
        await this.loadAssignedCashiers();
        await this.loadAvailableCashiers();
      } catch (error) {
        this.$modal.msgError("收银员移除失败");
      }
    },
    
    /** 保存配置 */
    handleSave() {
      this.$modal.msgSuccess("配置保存成功");
      this.$emit('refresh');
      this.handleClose();
    },
    
    /** 关闭对话框 */
    handleClose() {
      this.dialogVisible = false;
      this.activeTab = 'devices';
      this.selectedDevices = [];
      this.selectedCashiers = [];
    }
  }
};
</script>

<style scoped>
.relation-manage {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.available-section,
.assigned-section {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
}

.available-section h4,
.assigned-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.operation-section {
  display: flex;
  justify-content: center;
  gap: 10px;
  padding: 10px 0;
  border-top: 1px solid #e4e7ed;
  border-bottom: 1px solid #e4e7ed;
}

.dialog-footer {
  text-align: right;
}
</style>
